// @Description
// @Author  xiaoyang
// @Date  2023/5/5 2:28 下午

package middles

import (
	"github.com/gin-gonic/gin"
	systemControllers "golang-manage-admin/http/modules/system/controllers"
	"golang-manage-admin/lib"
	"golang-manage-admin/providers"
)

// CheckSign
// @Description:  签名验证
// @Author yang 2025-11-26 17:55:51
// @Return gin.HandlerFunc
func CheckSign() gin.HandlerFunc {
	controller := systemControllers.Controller{}
	return func(context *gin.Context) {

		var form lib.Sign
		//绑定参数
		if err := context.Bind(&form); err != nil {
			controller.BadResponse(10400, err.Error(), context)
			context.Abort()
			return
		}

		//保存需要签名校验的数据
		signMap := make(map[string]interface{})

		//所有get数据
		params := context.Request.URL.Query()
		if len(params) != 0 {
			for k, v := range params {
				if k != "_sign" && len(v) > 0 {
					//因为http.request在解析参数的时候会将同名的参数都放进同一个slice里，默认不允许请求端这样传参，所以这里直接用[0]获取到第一个
					signMap[k] = v[0]
				}
			}
		} else {
			if err := context.Request.ParseForm(); err != nil {
				controller.BadResponse(10001, "", context)
				context.Abort()
				return
			}
			//所有post数据(_sign除外)
			for k, v := range context.Request.PostForm {
				if k != "_sign" && len(v) > 0 {
					signMap[k] = v[0]
				}
			}
		}

		//生成签名
		serverSign := lib.ComGenSign(signMap, providers.Config.GetString("sign.rand_key"))

		//签名校验失败
		if serverSign != form.Sign {
			controller.BadResponse(10401, "", context)
			context.Abort()
			return
		}

		context.Next()
	}
}
